<?php
/**
 * [LupMisNotAllowedSync]
 * 本代码为系统自动生成代码，请根据自己业务进行修改;
 * 生成时间 2022-02-18 18:16:27;
 * 版权所有 2020-2022 lizhongwen，并保留所有权利;
 * 说明: 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；不允许对程序代码以任何形式任何目的的再发布;
 * 作者: 中文Lee;
 * 作者主页: http://www.lizhongwen.com;
 * 邮箱: 360811363@qq.com;
 * QQ: 360811363;
 */

namespace modules\sys\service\impl;

use application\component\BuildCodeComponent;
use application\core\Mapper;
use application\core\Result;
use application\core\SnowFlake;
use Exception;
use modules\sys\component\SetCacheComponent;
use modules\sys\mapper\ActionMapper;
use modules\sys\mapper\FieldMapper;
use modules\sys\mapper\MysqlMapper;
use modules\sys\mapper\PageMapper;
use modules\sys\mapper\TableMapper;
use modules\sys\service\FieldService;

class FieldServiceImpl implements FieldService
{
    function lists(array $data = [], array $pagePars = []): array
    {
        //查询数据表
        $fieldLists = [];
        if (!empty($data['table_name']) || !empty($data['field_name']) || !empty($data['field_remarks'])) {
            $fieldLists = FieldMapper::lists($data, $pagePars);
        }
        return [
            'code' => 200,
            'msg' => 'Success',
            'data' => $fieldLists
        ];
    }

    function query(array $data): array
    {
        return Result::success(false,FieldMapper::query($data));
    }

    function add(array $data): array
    {
        $queryRs = FieldMapper::query(['table_name' => $data['table_name'], 'field_name' => $data['field_name']]);
        if (!empty($queryRs)) {
            return Result::fail(false,[], "该字段已经存在！");
        }
        $data['id'] = SnowFlake::instance()->nextId();
        $add = FieldMapper::add($data);
        if ($add == 0) {
            return Result::fail(false,[], "添加失败");
        }
        //添加数据表字段
        $columnData = [
            'field_type' => $data['field_type'] ?? '',
            'table_name' => $data['table_name'] ?? '',
            'field_name' => $data['field_name'] ?? '',
            'field_len' => $data['field_len'] ?? '',
            'field_default_value' => $data['field_default_value'] ?? '',
            'field_remarks' => $data['field_remarks'] ?? ''
        ];
        try {
            MysqlMapper::addColumn($columnData);
        } catch (Exception $e) {
            SetCacheComponent::field();
            return Result::success(true,[], "字段添加成功，创建字段失败，请手动创建字段" . $e->getMessage());
        }
        SetCacheComponent::field();
        return Result::success(true,[], "添加成功");
    }

    function edit(array $data): array
    {
        $edit = FieldMapper::edit($data);
        if ($edit == 0) {
            return Result::fail(false,[], "修改失败");
        }
        //修改数据表字段
        $columnData = [
            'field_type' => $data['field_type'] ?? '',
            'table_name' => $data['table_name'] ?? '',
            'old_field_name' => $data['old_field_name'] ?? '',
            'field_name' => $data['field_name'] ?? '',
            'field_len' => $data['field_len'] ?? '',
            'field_default_value' => $data['field_default_value'] ?? '',
            'field_remarks' => $data['field_remarks'] ?? ''
        ];
        try {
            MysqlMapper::editColumn($columnData);
        } catch (Exception $e) {
            SetCacheComponent::field();
            return Result::success(true,[], "字段添加成功，创建字段失败，请手动创建字段" . $e->getMessage());
        }
        SetCacheComponent::field();
        return Result::success(true,[], "修改成功");
    }

    function queryByTableName(array $data): array
    {
        return Result::success(false,FieldMapper::queryByTableName($data));
    }

    function del(array $data): array
    {
        $del = FieldMapper::del(['id' => $data['ids']]);
        if ($del == 0) {
            return Result::fail(false,[], "删除失败，数据不存在");
        }
        SetCacheComponent::field();
        return Result::success(true,[], "删除成功");
    }

    function getTemplate(array $data): array
    {
        $buildCodeComponent = new BuildCodeComponent();
        return Result::success(false,$buildCodeComponent->buildCode($data['table_name']));
    }

    function syncCode(array $data): array
    {
        //判断是否同步页面
        $actions = $data['actions'];
        $pages = $data['pages'];
        $tableName = $data['table_name'];
        $buildCodeComponent = new BuildCodeComponent();
        $syncCodeMsg = $buildCodeComponent->syncCode($tableName, $pages);
        if (!empty($actions)) {
            //判断是否有lists
            $actionsArr = explode(",", $actions);
            if (in_array('lists', $actionsArr)) {
                //开始添加页面
                Mapper::beginTransaction();
                try {
                    //先添加页面,判断该页面是否存在
                    $tableNameArr = explode("_", $tableName);
                    $prefix = $tableNameArr[0];
                    $arr = [];
                    foreach ($tableNameArr as $k => $v) {
                        if ($k > 0) {
                            $arr[] = ucfirst($v);
                        }
                    }
                    $bigTableName = implode("", $arr);
                    $smallTableName = lcfirst($bigTableName);
                    $pageCode = $prefix . ":" . $smallTableName . ":lists";
                    $pageRs = PageMapper::queryByCode(['code' => $pageCode]);
                    $pageId = SnowFlake::instance()->nextId();
                    if (!empty($pageRs)) {
                        $syncCodeMsg[] = "<span style='color:red'>页面接口初始化失败（已经存在）</span>";
                        $pageId = $pageRs['id'];
                    }
                    //开始同步页面
                    $tableNameRs = TableMapper::queryByTableName(['table_name' => $tableName]);
                    $tableRemarks = $tableNameRs['table_remarks'];
                    $pageAddNum = 1;
                    if (empty($pageRs)) {
                        $addData = [
                            'id' => $pageId,
                            'page_name' => $tableRemarks,
                            'table_name' => $tableName,
                            'code' => $pageCode,
                            'jump' => 'pages/' . $prefix . '/' . $smallTableName,
                            'query_url' => str_replace(":", "/", $pageCode),
                            'api_url' => '#',
                            'status' => 1,
                            'sort' => 255,
                            'remarks' => '',
                            'page_type' => $tableNameRs['table_type']
                        ];
                        $pageAddNum = PageMapper::add($addData);
                        if ($pageAddNum == 0) {
                            $syncCodeMsg[] = "<span style='color:red'>页面以及操作功能同步失败。</span>";
                        } else {
                            $syncCodeMsg[] = "<span style='color:green'>页面接口同步成功</span>";
                        }
                    }

                    if ($pageAddNum > 0) {
                        //开始初始化操作功能
                        foreach ($actionsArr as $action) {
                            if ($action == 'add') {
                                //添加功能
                                $addActionRs = ActionMapper::queryByPageIdActionCode(['page_id' => $pageId, 'code' => $prefix . ":" . $smallTableName . ":add"]);
                                if (!empty($addActionRs)) {
                                    $syncCodeMsg[] = "<span style='color:red'>添加初始化失败（已经存在）</span>";
                                } else {
                                    $actionData = [
                                        'id' => SnowFlake::instance()->nextId(),
                                        'page_id' => $pageId,
                                        'action_name' => '添加',
                                        'table_name' => $tableName,
                                        'code' => $prefix . ":" . $smallTableName . ":add",
                                        'bind_event' => 'add',
                                        'tips' => '添加' . $tableRemarks,
                                        'bg_color' => '#009688',
                                        'target_type' => 'openFrame',
                                        'width' => '100%',
                                        'height' => '100%',
                                        'jump' => 'add.html',
                                        'query_url' => '#',
                                        'api_url' => $prefix . "/" . $smallTableName . "/add",
                                        'status' => 1,
                                        'sort' => 255
                                    ];
                                    $actionAdd = ActionMapper::add($actionData);
                                    if ($actionAdd == 0) {
                                        $syncCodeMsg[] = "<span style='color:red'>添加功能同步失败。</span>";
                                    } else {
                                        $syncCodeMsg[] = "<span style='color:green'>添加功能同步成功</span>";
                                    }
                                }
                            } elseif ($action == 'del') {
                                //添加功能
                                $addActionRs = ActionMapper::queryByPageIdActionCode(['page_id' => $pageId, 'code' => $prefix . ":" . $smallTableName . ":del"]);
                                if (!empty($addActionRs)) {
                                    $syncCodeMsg[] = "<span style='color:red'>删除初始化失败（已经存在）</span>";
                                } else {
                                    $actionData = [
                                        'id' => SnowFlake::instance()->nextId(),
                                        'page_id' => $pageId,
                                        'action_name' => '删除',
                                        'table_name' => $tableName,
                                        'code' => $prefix . ":" . $smallTableName . ":del",
                                        'bind_event' => 'del',
                                        'tips' => '确定要删除选中的数据吗？',
                                        'bg_color' => '#ff5722',
                                        'target_type' => 'doApi',
                                        'width' => '100%',
                                        'height' => '100%',
                                        'jump' => '#',
                                        'query_url' => '#',
                                        'api_url' => $prefix . "/" . $smallTableName . "/del",
                                        'status' => 1,
                                        'sort' => 255
                                    ];
                                    $actionAdd = ActionMapper::add($actionData);
                                    if ($actionAdd == 0) {
                                        $syncCodeMsg[] = "<span style='color:red'>删除功能同步失败。</span>";
                                    } else {
                                        $syncCodeMsg[] = "<span style='color:green'>删除功能同步成功</span>";
                                    }
                                }
                            } elseif ($action == 'delAll') {
                                //添加功能
                                $addActionRs = ActionMapper::queryByPageIdActionCode(['page_id' => $pageId, 'code' => $prefix . ":" . $smallTableName . ":delAll"]);
                                if (!empty($addActionRs)) {
                                    $syncCodeMsg[] = "<span style='color:red'>批量删除初始化失败（已经存在）</span>";
                                } else {
                                    $actionData = [
                                        'id' => SnowFlake::instance()->nextId(),
                                        'page_id' => $pageId,
                                        'action_name' => '批量删除',
                                        'table_name' => $tableName,
                                        'code' => $prefix . ":" . $smallTableName . ":delAll",
                                        'bind_event' => 'del',
                                        'tips' => '确定要删除选中的数据吗？',
                                        'bg_color' => '#ff0000',
                                        'target_type' => 'doApi',
                                        'width' => '100%',
                                        'height' => '100%',
                                        'jump' => '#',
                                        'query_url' => '#',
                                        'api_url' => $prefix . "/" . $smallTableName . "/delAll",
                                        'status' => 1,
                                        'sort' => 255
                                    ];
                                    $actionAdd = ActionMapper::add($actionData);
                                    if ($actionAdd == 0) {
                                        $syncCodeMsg[] = "<span style='color:red'>批量删除功能同步失败。</span>";
                                    } else {
                                        $syncCodeMsg[] = "<span style='color:green'>批量删除功能同步成功</span>";
                                    }
                                }
                            } elseif ($action == 'edit') {
                                //编辑功能
                                $addActionRs = ActionMapper::queryByPageIdActionCode(['page_id' => $pageId, 'code' => $prefix . ":" . $smallTableName . ":edit"]);
                                if (!empty($addActionRs)) {
                                    $syncCodeMsg[] = "<span style='color:red'>编辑初始化失败（已经存在）</span>";
                                } else {
                                    $actionData = [
                                        'id' => SnowFlake::instance()->nextId(),
                                        'page_id' => $pageId,
                                        'action_name' => '编辑',
                                        'table_name' => $tableName,
                                        'code' => $prefix . ":" . $smallTableName . ":edit",
                                        'bind_event' => 'edit',
                                        'tips' => '编辑' . $tableRemarks,
                                        'bg_color' => '#1e9fff',
                                        'target_type' => 'openFrame',
                                        'width' => '100%',
                                        'height' => '100%',
                                        'jump' => 'edit.html',
                                        'query_url' => $prefix . "/" . $smallTableName . "/query",
                                        'api_url' => $prefix . "/" . $smallTableName . "/edit",
                                        'status' => 1,
                                        'sort' => 255
                                    ];
                                    $actionAdd = ActionMapper::add($actionData);
                                    if ($actionAdd == 0) {
                                        $syncCodeMsg[] = "<span style='color:red'>编辑功能同步失败。</span>";
                                    } else {
                                        $syncCodeMsg[] = "<span style='color:green'>编辑功能同步成功</span>";
                                    }
                                }
                            }
                        }
                    }
                    Mapper::commit();
                } catch (Exception $e) {
                    Mapper::rollBack();
                    $syncCodeMsg[] = "<span style='color:red'>页面以及操作功能同步失败！" . $e->getMessage() . "</span>";
                }
            }
            SetCacheComponent::page();
        }

        return Result::success(false,$syncCodeMsg);
    }
}